package com.xjrsoft.module.iot.service.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.DatasourceUtil;
import com.xjrsoft.module.iot.dto.GetDatasourceDto;
import com.xjrsoft.module.iot.entity.IotDic;
import com.xjrsoft.module.iot.service.IIotDatasourceService;
import com.xjrsoft.module.iot.service.IIotDicService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: tzx
 * @Date: 2024/5/30 11:20
 */
@Service
@AllArgsConstructor
public class IotDatasourceServiceImpl implements IIotDatasourceService {

    private final IIotDicService iotDicService;
    @Override
    @SneakyThrows
    public List<Object> getDatasource(GetDatasourceDto dto) {

        LambdaQueryWrapper<IotDic> queryWrapper = Wrappers.lambdaQuery(IotDic.class).in(IotDic::getId, dto.getIds());

        List<IotDic> list = iotDicService.list(queryWrapper);

        Map<String, List<IotDic>> iotGroup = list.stream().collect(Collectors.groupingBy(IotDic::getSaveDb));

        List<Object> result = new ArrayList<>();

        //遍历分组 找到同一个数据库连接的字典 统一查询
        for (Map.Entry<String, List<IotDic>> group : iotGroup.entrySet()) {

            List<String> allDic = group.getValue().stream().map(IotDic::getName).collect(Collectors.toList());

            Db db = Db.use(DatasourceUtil.getDataSource(group.getKey()));

//            String collect = allDic.stream().collect(Collectors.joining("','"));

            List<Entity> query = db.query("SELECT * FROM  cy_data where (var_name,var_time) in ( select var_name ,MAX(var_time)  from cy_data where var_name in (?) group by var_name)", allDic);

            result.addAll(query);
        }


        return result;
    }
}
